package com.ruoyi.merchant.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.exception.ServiceException;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SkuIdGenerator;
import com.ruoyi.merchant.domain.*;
import com.ruoyi.merchant.domain.dto.DishDetailUpdateDTO;
import com.ruoyi.merchant.domain.dto.DishSubmitDTO;
import com.ruoyi.merchant.domain.dto.SkuDTO;
import com.ruoyi.merchant.domain.dto.SkuPriceStockUpdateDTO;
import com.ruoyi.merchant.domain.dto.SpecGroupDTO;
import com.ruoyi.merchant.mapper.*;
import com.ruoyi.merchant.service.IProductService;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 商品Service业务层处理
 */
@Service
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductSpecGroupMapper specGroupMapper;

    @Autowired
    private ProductSpecDetailMapper specDetailMapper;

    @Autowired
    private MerchantDishAuditMapper dishAuditMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Product selectProductByProductId(Long productId) {
        Product product = productMapper.selectProductByProductId(productId);
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        if (product != null && !merchantId.equals(product.getMerchantId())) {
            throw new ServiceException("无权访问该商品");
        }

        // 加载规格信息
        if (product != null) {
            List<ProductSpecGroup> specGroups = specGroupMapper.selectByProductId(productId);
            product.setSpecGroups(specGroups);

            List<ProductSpecDetail> skuList = specDetailMapper.selectByProductId(productId);
            product.setSkuList(skuList);
        }

        return product;
    }

    @Override
    public List<Product> selectProductList(Product product) {
        product.setMerchantId(MerchantSecurityUtils.getMerchantId());
        return productMapper.selectProductList(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertProductAndSubmitAudit(DishSubmitDTO dishSubmitDTO) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        // 1. 计算商品的基础信息
        int totalStock = 0;
        BigDecimal minPrice = null;
        BigDecimal maxMarketPrice = null;

        for (SkuDTO sku : dishSubmitDTO.getSkuList()) {
            totalStock += sku.getStock();
            if (minPrice == null || sku.getPrice().compareTo(minPrice) < 0) {
                minPrice = sku.getPrice();
            }
            if (sku.getMarketPrice() != null) {
                if (maxMarketPrice == null || sku.getMarketPrice().compareTo(maxMarketPrice) > 0) {
                    maxMarketPrice = sku.getMarketPrice();
                }
            }
        }

        // 2. 创建商品记录
        Category category = categoryMapper.selectCategoryByCategoryId(dishSubmitDTO.getCategoryId());
        String categoryName = category.getName();
        Product product = new Product();
        product.setCategoryName(categoryName);
        product.setMerchantId(merchantId);
        product.setCategoryId(dishSubmitDTO.getCategoryId());
        product.setName(dishSubmitDTO.getDishName());
        product.setDescription(dishSubmitDTO.getDescription());
        product.setImageUrl(dishSubmitDTO.getImageUrl());
        product.setRegionPrice(minPrice); // 使用最低价作为区域价
        product.setMarketPrice(maxMarketPrice); // 使用最高市场价
        product.setStockQuantity(totalStock);
        product.setSalesCount(0);
        product.setAuditStatus(0); // 待审核
        product.setStatus(0); // 下架
        product.setSortOrder(0);

        int result = productMapper.insertProduct(product);
        if (result <= 0) {
            throw new ServiceException("创建商品失败");
        }

        Long productId = product.getProductId();

        // 3. 创建规格分组
        if (dishSubmitDTO.getSpecGroups() != null && !dishSubmitDTO.getSpecGroups().isEmpty()) {
            List<ProductSpecGroup> groupList = new ArrayList<>();
            for (int i = 0; i < dishSubmitDTO.getSpecGroups().size(); i++) {
                SpecGroupDTO dto = dishSubmitDTO.getSpecGroups().get(i);
                ProductSpecGroup group = new ProductSpecGroup();
                group.setGroupId(i + 1);
                group.setProductId(productId);
                group.setGroupName(dto.getGroupName());
                group.setSortOrder(dto.getSortOrder() != null ? dto.getSortOrder() : i);
                // 将规格选项保存到预留字段
                group.setExternField1(JSON.toJSONString(dto.getSpecOptions()));
                groupList.add(group);
            }
            specGroupMapper.batchInsert(groupList);
        }

        // 4. 创建SKU记录
        if (dishSubmitDTO.getSkuList() != null && !dishSubmitDTO.getSkuList().isEmpty()) {
            List<ProductSpecDetail> detailList = new ArrayList<>();
            for (int i = 0; i < dishSubmitDTO.getSkuList().size(); i++) {
                SkuDTO dto = dishSubmitDTO.getSkuList().get(i);
                ProductSpecDetail detail = new ProductSpecDetail();
                detail.setGroupId(productId); // 使用productId关联
                detail.setSpecItems(dto.getSpecItems());
                detail.setSkuId(SkuIdGenerator.generateSkuId()); // ⭐ 改为雪花算法
                detail.setPrice(dto.getPrice());
                detail.setMarketPrice(dto.getMarketPrice());
                detail.setStock(dto.getStock());
                detail.setSortOrder(dto.getSortOrder() != null ? dto.getSortOrder() : i);
                detail.setIsOnSale(1); // 默认上架
                detailList.add(detail);
            }
            specDetailMapper.batchInsert(detailList);
        }

        // 5. 创建审核记录
        Merchant merchant = merchantMapper.selectMerchantById(merchantId);
        String merchantName = merchant.getMerchantName();

        MerchantDishAudit audit = new MerchantDishAudit();
        audit.setMerchantName(merchantName);
        audit.setMerchantId(merchantId);
        audit.setDishId(productId);
        audit.setDishName(dishSubmitDTO.getDishName());
        audit.setCategoryId(dishSubmitDTO.getCategoryId());
        audit.setPrice(minPrice);
        audit.setDescription(dishSubmitDTO.getDescription());
        audit.setImageUrl(dishSubmitDTO.getImageUrl());
        audit.setDishTags(dishSubmitDTO.getDishTags());
        audit.setIsRecommended(dishSubmitDTO.getIsRecommended());
        audit.setStockQuantity(totalStock);
        audit.setSalesCount(0);
        audit.setDishStatus("0"); // 下架状态
        audit.setAuditStatus("0"); // 待审核
        audit.setApplicationTime(new Date());
        audit.setCreateBy(SecurityUtils.getUsername());

        audit.setRemark("商家申请上架:"+dishSubmitDTO.getDishName());

        // 保存规格信息到JSON
        Map<String, Object> specsData = new HashMap<>();
        specsData.put("specGroups", dishSubmitDTO.getSpecGroups());
        specsData.put("skuList", dishSubmitDTO.getSkuList());
        audit.setDishSpecs(JSON.toJSONString(specsData));

        dishAuditMapper.insertDishAudit(audit);

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateProductDetailAndSubmitAudit(DishDetailUpdateDTO dishDetailUpdateDTO) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        Long dishId = dishDetailUpdateDTO.getDishId();

        // 1. 验证商品是否存在且属于当前商家
        Product product = productMapper.selectProductByProductId(dishId);
        if (product == null) {
            throw new ServiceException("商品不存在");
        }
        if (!merchantId.equals(product.getMerchantId())) {
            throw new ServiceException("无权修改该商品");
        }
        // ⭐ 2. 将该商品的所有旧审核记录标记为历史记录
        dishAuditMapper.markHistoryByDishId(dishId);

        // 3. 更新商品基本信息
        Product updateProduct = new Product();
        updateProduct.setProductId(dishId);
        updateProduct.setMerchantId(merchantId);
        updateProduct.setCategoryId(dishDetailUpdateDTO.getCategoryId());
        updateProduct.setName(dishDetailUpdateDTO.getDishName());
        updateProduct.setDescription(dishDetailUpdateDTO.getDescription());
        updateProduct.setImageUrl(dishDetailUpdateDTO.getImageUrl());
        updateProduct.setAuditStatus(0); // 重置为待审核
        updateProduct.setStatus(0); // 自动下架

        int result = productMapper.updateProduct(updateProduct);

        // 4. 查询现有规格信息
        List<ProductSpecGroup> specGroups = specGroupMapper.selectByProductId(dishId);
        List<ProductSpecDetail> skuList = specDetailMapper.selectByProductId(dishId);

        // 5. 创建新的审核记录

        Merchant merchant = merchantMapper.selectMerchantById(merchantId);
        String merchantName = merchant.getMerchantName();
        MerchantDishAudit audit = new MerchantDishAudit();
        audit.setMerchantName(merchantName);
        audit.setMerchantId(merchantId);
        audit.setDishId(dishId);
        audit.setDishName(dishDetailUpdateDTO.getDishName());
        audit.setCategoryId(dishDetailUpdateDTO.getCategoryId());
        audit.setDescription(dishDetailUpdateDTO.getDescription());
        audit.setImageUrl(dishDetailUpdateDTO.getImageUrl());
        audit.setDishTags(dishDetailUpdateDTO.getDishTags());
        audit.setIsRecommended(dishDetailUpdateDTO.getIsRecommended());
        audit.setAuditStatus("0"); // 待审核
        audit.setApplicationTime(new Date());
        audit.setCreateBy(SecurityUtils.getUsername());
        audit.setDelFlag("0");

        audit.setRemark("商家修改后重新申请上架");

        // 6. 计算价格和库存
        int totalStock = 0;
        BigDecimal minPrice = null;
        for (ProductSpecDetail sku : skuList) {
            totalStock += sku.getStock();
            if (minPrice == null || sku.getPrice().compareTo(minPrice) < 0) {
                minPrice = sku.getPrice();
            }
        }
        audit.setStockQuantity(totalStock);
        audit.setPrice(minPrice);
        audit.setDishStatus(product.getStatus().toString());
        audit.setSalesCount(product.getSalesCount());

        // 7. 保存现有规格信息到JSON
        Map<String, Object> specsData = new HashMap<>();
        specsData.put("specGroups", specGroups);
        specsData.put("skuList", skuList);
        audit.setDishSpecs(JSON.toJSONString(specsData));

        dishAuditMapper.insertDishAudit(audit);

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSkuPriceAndStock(SkuPriceStockUpdateDTO dto) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        // 1. 验证SKU是否存在
        ProductSpecDetail sku = specDetailMapper.selectBySkuId(dto.getSkuId());
        if (sku == null) {
            throw new ServiceException("SKU不存在");
        }

        // 2. 查询SKU所属的商品
        Long productId = specDetailMapper.selectProductIdBySkuId(dto.getSkuId());
        Product product = productMapper.selectProductByProductId(productId);
        if (product == null || !merchantId.equals(product.getMerchantId())) {
            throw new ServiceException("无权修改该SKU");
        }

        // 3. 更新SKU价格和库存
        ProductSpecDetail updateSku = new ProductSpecDetail();
        updateSku.setSkuId(dto.getSkuId());
        updateSku.setPrice(dto.getPrice());
        updateSku.setStock(dto.getStock());
        updateSku.setMarketPrice(dto.getMarketPrice());

        int result = specDetailMapper.updatePriceAndStock(updateSku);

        // 4. 重新计算商品总库存和价格
        if (result > 0) {
            List<ProductSpecDetail> allSkus = specDetailMapper.selectByProductId(productId);
            int totalStock = 0;
            BigDecimal minPrice = null;
            BigDecimal maxMarketPrice = null;

            for (ProductSpecDetail item : allSkus) {
                totalStock += item.getStock();
                if (minPrice == null || item.getPrice().compareTo(minPrice) < 0) {
                    minPrice = item.getPrice();
                }
                if (item.getMarketPrice() != null) {
                    if (maxMarketPrice == null || item.getMarketPrice().compareTo(maxMarketPrice) > 0) {
                        maxMarketPrice = item.getMarketPrice();
                    }
                }
            }

            Product updateProduct = new Product();
            updateProduct.setProductId(productId);
            updateProduct.setStockQuantity(totalStock);
            updateProduct.setRegionPrice(minPrice);
            updateProduct.setMarketPrice(maxMarketPrice);
            productMapper.updateProduct(updateProduct);
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteProductByProductIds(Long[] productIds) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        for (Long productId : productIds) {
            Product product = productMapper.selectProductByProductId(productId);
            if (product == null || !merchantId.equals(product.getMerchantId())) {
                throw new ServiceException("包含无权删除的商品");
            }

            // 删除规格分组（软删除）
            specGroupMapper.deleteByProductId(productId);

            // 删除SKU
            specDetailMapper.deleteByProductId(productId);
        }
        return productMapper.deleteProductByProductIds(productIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteProductByProductId(Long productId) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        Product product = productMapper.selectProductByProductId(productId);
        if (product == null || !merchantId.equals(product.getMerchantId())) {
            throw new ServiceException("无权删除该商品");
        }

        // 删除规格分组（软删除）
        specGroupMapper.deleteByProductId(productId);

        // 删除SKU
        specDetailMapper.deleteByProductId(productId);

        return productMapper.deleteProductByProductId(productId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateProductStatus(Long[] productIds, Integer status) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        // 如果是上架操作，需要验证审核状态
        if (status == 1) {
            for (Long productId : productIds) {
                Product product = productMapper.selectProductByProductId(productId);
                if (product == null || !merchantId.equals(product.getMerchantId())) {
                    throw new ServiceException("包含无权操作的商品");
                }

                // 检查审核状态
                if (product.getAuditStatus() != 1) {
                    throw new ServiceException("商品【" + product.getName() + "】未通过审核，不能上架");
                }
            }
        } else {
            // 下架操作只需要验证权限
            for (Long productId : productIds) {
                Product product = productMapper.selectProductByProductId(productId);
                if (product == null || !merchantId.equals(product.getMerchantId())) {
                    throw new ServiceException("包含无权操作的商品");
                }
            }
        }

        return productMapper.updateProductStatus(productIds, status, merchantId);
    }

    @Override
    public Map<String, Object> selectProductStatistics() {
        return productMapper.selectProductStatistics(MerchantSecurityUtils.getMerchantId());
    }
}
